package servlet.chat;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Chat;
import model.ChatUser;
import model.ChatUsers;
import model.Room;
import model.Rooms;
import model.User;
import model.Users;
import model.db.UsersDB;

/**
 *
 * @author user
 */
public class ChatServlet extends HttpServlet {

    ChatUsers chatUsers;
    ChatUsers chatRooms;

    @Override
    public void init() throws ServletException {
        super.init();

        // Get Servlet Context
        ServletContext sc = getServletContext();

        // Create Object
        chatUsers = new ChatUsers();
        chatRooms = new ChatUsers();

        // Add object to application session
        sc.setAttribute("chatUsers", chatUsers);
        sc.setAttribute("chatRooms", chatRooms);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get login user
        Users loginUsers = (Users) getServletContext().getAttribute("loginUsers");

        // Get rooms
        Rooms rooms = (Rooms) getServletContext().getAttribute("rooms");

        String strOut = "{}";

        // Save a chat
        if (request.getParameter("action").equalsIgnoreCase("send")) {
            saveChat(request);
        }

        // Recieve Chats
        if (request.getParameter("action").equalsIgnoreCase("recieve")) {
            strOut = recieveChat(request);
        }

        // Join to a room
        if (request.getParameter("action").equalsIgnoreCase("join")) {
            int userId = (Integer) request.getSession().getAttribute("id");
            int roomId = Integer.parseInt(request.getParameter("roomId"));
            User user = loginUsers.find(userId);
            Room room;

            System.out.println("join");
            if (user != null) {
                room = rooms.find(roomId);
                if (room != null) {
                    if (room.addJoinUser(user)) {
                        strOut = "{success:\"true\"}";
                    } else {
                        strOut = "{success:\"false\"}";
                    }
                }
            }
        }

        // Unjoin senderName a room
        if (request.getParameter("action").equalsIgnoreCase("unjoin")) {
            int userId = (Integer) request.getSession().getAttribute("id");
            int roomId = Integer.parseInt(request.getParameter("roomId"));
            rooms.removeJoinUser(userId, roomId);
        }

        // Get join users in a room
        if (request.getParameter("action").equalsIgnoreCase("joinUsers")) {
            int roomId = Integer.parseInt(request.getParameter("roomId"));
            Room room;

            room = rooms.find(roomId);
            if (room != null) {
                strOut = (new Gson()).toJson(room.joinUsers);
            }
        }

        if (request.getParameter("action").equalsIgnoreCase("info")) {
            String name = request.getParameter("name");
            String username = (String) request.getSession().getAttribute("username");
            int senderId = (Integer) request.getSession().getAttribute("id");
            UsersDB usersDB = new UsersDB();
            User user = usersDB.find(name);
            Room room = null;
            String desc;

            if (user == null) {
                room = rooms.find(name);
                if (room != null) {
                    desc =
                            "name : #" + room.name + "\n"
                            + "kategori : " + room.categoryId + "\n"
                            + "owner : " + room.ownerId + "\n"
                            + "persistance : " + ((room.persistance) ? "yes" : "no");
                } else {
                    desc = "User or room #" + name + " not found.";
                }
            } else {
                desc =
                        "username : #" + user.username + "\n"
                        + "role : " + user.role + "\n";
            }
            strOut = desc;
        }

        // Out
        PrintWriter out = response.getWriter();
        response.setContentType("text/plain;charset=UTF-8");
        try {
            out.print(strOut);
        } finally {
            out.close();
        }
    }

    private String recieveChat(HttpServletRequest request) throws NumberFormatException {
        String strOut = "";

        String type = request.getParameter("type");
        String strId = request.getParameter("id");

        int id = Integer.parseInt(strId);
        String strLastId = request.getParameter("lastId");

        int lastId = Integer.parseInt(strLastId);
        System.out.println("lastId : " + lastId);

        // Find chatUser or chat room
        int userId;
        ChatUser chatContainer;
        if (type.equals("user")) {
            userId = (Integer) request.getSession().getAttribute("id");
            chatContainer = chatUsers.find(userId);
        } else {
            chatContainer = chatRooms.find(id);
        }

        if (chatContainer != null) {
            // Get chats
            ArrayList<model.Chat> chats = chatContainer.find(lastId, id, type);

            // To JSON
            Gson gson = new Gson();
            strOut = gson.toJson(chats);
            System.out.println("chats length : " + chats.size());
            System.out.println("str out : " + strOut);
        }

        return strOut;
    }

    private void saveChat(HttpServletRequest request) throws NumberFormatException {
        String type = request.getParameter("type");

        String strSenderId = request.getParameter("senderId");
        int senderId = (Integer) request.getSession().getAttribute("id");
        System.out.println("senderId : " + senderId);

        String strRecieverId = request.getParameter("recieverId");
        int recieverId = Integer.parseInt(strRecieverId);
        System.out.println("recieverId : " + recieverId);

        String content = request.getParameter("content");
        System.out.println("content : " + content);

        String username = (String) request.getSession().getAttribute("username");
        if (type.equalsIgnoreCase("user")) {
            System.out.println("user");
            // Add to reciever
            chatUsers.add(username, senderId, recieverId, content);

            // Add to it's self
            chatUsers.add(username, recieverId, senderId, content);
        } else if (type.equals("room")) {
            // Add chat to room
            chatRooms.add(username, senderId, recieverId, content);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
